import Layer from '../../core/Layer';


export default class extends Layer {
    constructor(canvas, style) {
        super(canvas, style);
        this.series = [];
        this.xAxis = null;
        this.yAxis = null;
        this.count = style.count || 30;
        this.shift = style.shift || 0;
        this.gutter = style.gutter || 10;
    }

    setXAxis(xAxis) {
        this.xAxis = xAxis;
    }

    setYAxis(yAxis) {
        this.yAxis = yAxis;
    }

    addSeries(line) {
        this.series.push(line);
    }

    build(painter) {
        this.childs.splice(0);
        let max = Number.MIN_VALUE;
        let min = Number.MAX_VALUE;
        for (let i = 0; i < this.series.length; i++) {
            this.series[i].getMinMax();
            if (min > this.series[i].min) {
                min = this.series[i].min;
            }
            if (max < this.series[i].max) {
                max = this.series[i].max;
            }
        }
        let absValue = Math.abs(max) > Math.abs(min) ? Math.abs(max) : Math.abs(min);
        let axisMin = 0;
        let axisMax = 0;
        if (min >= 0) {
            axisMax = absValue;
            axisMin = 0;
        } else if (max > 0) {
            axisMax = absValue;
            axisMin = - absValue;
        } else {
            axisMax = 0;
            axisMin = - absValue;
        }
        this.yAxis.bottom = this.xAxis.height;
        this.yAxis.height = this.height - this.xAxis.height;
        this.xAxis.left = this.yAxis.width;
        this.xAxis.width = this.width - this.yAxis.width;
        this.xAxis.max = axisMax;
        this.xAxis.min = axisMin;
        this.addChild(this.xAxis, this.yAxis);
        const yStep = (this.height - this.xAxis.height) / this.yAxis.data.length;
        const barHeight = (yStep - 2 * this.gutter) / this.series.length;
        const xStep = (this.width - this.yAxis.width) / (axisMax - axisMin);
        for (let i = 0; i < this.series.length; i++) {
            const series = this.series[i];
            series.left = this.yAxis.width;
            series.bottom = this.gutter + i * barHeight + this.xAxis.height;
            series.height = this.height - this.xAxis.height;
            series.width = this.width - this.yAxis.width;
            series.barHeight = barHeight;
            series.yStep = yStep;
            series.xStep = xStep;
            series.base = (0 - axisMin) * xStep;
            this.addChild(series);
        }
    }
}
